package net.yambal.android.secretary_alarm.file;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.media.MediaPlayer;
import android.util.Log;

public class VoicePlayManager implements MediaPlayer.OnCompletionListener{
	private static VoicePlayManager _my_instance = null;
	private List<ListenerVoicePlayManager> _listener;
	private Boolean _isPlaying = false;
	private List<File> _que;
	private MediaPlayer _mp;
	
	public VoicePlayManager(ListenerVoicePlayManager listener) {
		_listener = new ArrayList<ListenerVoicePlayManager>();
		_listener.add(listener);
		_que = new ArrayList<File>();
	}
	
	synchronized static
	public VoicePlayManager getInstance(ListenerVoicePlayManager listener){
		if ( _my_instance == null ){
			_my_instance = new VoicePlayManager(listener);
		}else{
			_my_instance._listener.add(listener);
		}
		return _my_instance;
	}
	
	public void play(File voice_file){
		if(_isPlaying){
			_que.add(voice_file);
		}else{
			inner_play(voice_file);
		}
	}
	
	private void inner_play(File voice_file){
		if(voice_file.exists()){
			try {
				_isPlaying = true;
				Log.d("sa", "inner_play@VoiceStackPlayer " + voice_file.getPath());
				_mp = new MediaPlayer();
				_mp.setOnCompletionListener(this);
				_mp.setDataSource(voice_file.getPath());
				_mp.prepare();
				_mp.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// MediaPlayer.OnCompletionListener
	@Override
	public void onCompletion(MediaPlayer arg0) {
		if(_que.size() > 0){
			File voice_file = _que.remove(0);
			inner_play(voice_file);
		}else{
			_isPlaying = false;
			onEndAll();
		}
	}
	
	private void onEndAll(){
		while(_listener.size() != 0){
			ListenerVoicePlayManager listener = _listener.remove(0);
			listener.onVoicePlayCompletion();
		}
	}
}
